/**
 * @comment Interaction.java
 * @author Mojianliang 
 * @date 2013-8-15
 */
package com.all.widget;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;



/**
 * @comment 主要用拍照、摄像、录音 
 * @author MoJianLiang 
 * @version v1.0
 * @date 2013-8-15
 */
public class Interaction extends RelativeLayout implements OnClickListener  {

	public Interaction(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}

	/*Button mTakephotoButton=null;
	Button mVideoButton=null;
	Button mRadioButton=null;
	OkayPicturesGallery mphotoGallery = null;
	ViewGalleryAdapter mPhotoGalleryAdapter = null;
	LinearLayout mBoundphotoLayout=null;//外框
	OkayPicturesGallery mVideoGallery = null;
	ViewGalleryAdapter mVideoGalleryAdapter = null;
	LinearLayout mBoundvideoLayout=null;//外框
	OkayPicturesGallery mRadioGallery = null;
	ViewGalleryAdapter mRadioGalleryAdapter = null;
	LinearLayout mBoundradioLayout=null;//外框
	BaseActivity mActivity=null;
    String mImagePathString=null;
    String mRadioPathString=null;
    String mVideoPathString=null;
    Context mContext=null;
    
    int flag=0;//默认为本地，1为网络

    *//**
     * 
     * @param 默认为本地，大于 0时为网络
     *//*
	void setFlag(int flag) {
		if (flag>0)
			this.flag=1;
		else
			this.flag = flag;
	}
	*//**
     * 此方法必须先调用
     * @param activity
     *//*
    public void setActivity(BaseActivity activity)
    {
    	if (mActivity==null)
    	{
    	  mActivity=activity;
    	  mActivity.setonResultActivityLinerener(new onResultActivityLinerener() {
			
			@Override
			public void onActivityResult(int requestCode, int resultCode, Intent data) {
				
				switch (requestCode) {
				case UIHelper.RESULT_CAPTURE_IMAGE:// 拍照
					if (resultCode ==android.app.Activity. RESULT_OK) {
						addPhoto(mImagePathString);
					}
					break;
				case UIHelper.REQUEST_CODE_TAKE_VIDEO:// 拍摄视频
					if (resultCode == android.app.Activity. RESULT_OK) {
						Uri uriVideo = data.getData();
						Cursor cursor = mActivity.getContentResolver().query(uriVideo, null,
								null, null, null);
						if (cursor.moveToNext()) {
							*//** _data：文件的绝对路径 ，_display_name：文件名 *//*
							mVideoPathString = cursor.getString(cursor
									.getColumnIndex("_data"));
			                addVideo(mVideoPathString);
						}
						cursor.close();
					}
					break;
					case UIHelper.RESULT_CAPTURE_RECORDER_SOUND:// 录音
					if (resultCode == android.app.Activity. RESULT_OK) {
//						Uri uriRecorder = data.getData();
//						mRadioPathString = uriRecorder.getPath();
						
						  String filePath = null;
			                Uri uriRecorder = data.getData();
			                Log.d("","URI = "+ uriRecorder);                                       
			                if (uriRecorder != null && "content".equals(uriRecorder.getScheme())) {
			                    Cursor cursor = mActivity.getContentResolver().query(uriRecorder, new String[] { android.provider.MediaStore.Audio.Media.DATA }, null, null, null);
			                    cursor.moveToFirst();   
			                    filePath = cursor.getString(0);
			                    cursor.close();
			                }
			                else {
			                    filePath = uriRecorder.getPath();
			                }
			                Log.d("","Chosen path = "+ filePath);
			                mRadioPathString=filePath;
						
	                    addRadio(mRadioPathString);
					}
					break;
					 case  UIHelper.RESULT_LOAD_IMAGE:
					 {
					     if (resultCode == Activity.RESULT_OK && null != data) {
					            Uri selectedImage = data.getData();
					            String[] filePathColumn = { MediaStore.Images.Media.DATA };
					 
					            Cursor cursor =mActivity.getContentResolver().query(selectedImage,
					                    filePathColumn, null, null, null);
					            cursor.moveToFirst();
					 
					            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
					            String picturePath = cursor.getString(columnIndex);
					            cursor.close();
//					            mImagePathString=picturePath;
								addPhoto(picturePath);
					        }
					 }
					 break;
				}
			}
		});
    	}
    }
    private void layout(OkayPicturesGallery okayPicturesGallery,ViewGalleryAdapter viewGalleryAdapter)
    {
		LinearLayout layout = (LinearLayout) okayPicturesGallery.findViewById(R.id.linear_id);
		ViewGroup.LayoutParams params = layout.getLayoutParams();
		params.width = getResources().getDimensionPixelSize(
				R.dimen.gallery_item_width)
				* (viewGalleryAdapter.getCount())
				+ getResources().getDimensionPixelOffset(
						R.dimen.gallery_spacing)
				* (viewGalleryAdapter.getCount() - 1);
    }
	public Interaction(Context context, AttributeSet attrs) {
		super(context, attrs);
		LayoutInflater.from(context).inflate(R.layout.com_interaction,this,true);
		mContext=context;
		initalData();
   }
	public Interaction(Context context) {
		super(context, null);
		LayoutInflater.from(context).inflate(R.layout.com_interaction,this,true);
		mContext=context;
		initalData();
    }
	*//**
	 * 
	 * @param context
	 * @param flag //默认为本地，1为网络 下载 
	 *//*
	public Interaction(Context context,int flag) {
		super(context, null);
		LayoutInflater.from(context).inflate(R.layout.com_interaction,this,true);
		mContext=context;
		setFlag(flag);
		initalData();
    }
    LinearLayout mtakephotoLayout=null;
    LinearLayout mvideolLayout=null;
    LinearLayout mradiolayLayout=null;
 	private void initalData()
	{
 		mtakephotoLayout=(LinearLayout) findViewById(R.id.interaction_activity_takephoto);
 		((TextView)mtakephotoLayout.findViewById(R.id.com_outsideinfo_title)).setText(getResources().getString(R.string.takephoto));
 		mTakephotoButton=(Button) mtakephotoLayout.findViewById(R.id.com_outsideinfo_add);
 		mTakephotoButton.setBackground(mContext.getResources().getDrawable(R.drawable.com_interaction_takephoto));
 		
 		mBoundphotoLayout=(LinearLayout) mtakephotoLayout.findViewById(R.id.com_interaction_linearlayoutframe);
 		
		mphotoGallery = (OkayPicturesGallery) mtakephotoLayout.findViewById(R.id.com_outsideinfo_gallery);
		mPhotoGalleryAdapter = new ViewGalleryAdapter(mContext, flag==0?UIHelper.GALLERY:UIHelper.UrlGALLERY);
		mphotoGallery.setAdapter(mPhotoGalleryAdapter);
		
		
		mvideolLayout=(LinearLayout) findViewById(R.id.interaction_activity_video);
 		((TextView)mvideolLayout.findViewById(R.id.com_outsideinfo_title)).setText(getResources().getString(R.string.takevideo));
 		mVideoButton=(Button) mvideolLayout.findViewById(R.id.com_outsideinfo_add);
 		mVideoButton.setBackground(mContext.getResources().getDrawable(R.drawable.com_interaction_video));
 		
 		mBoundvideoLayout=(LinearLayout) mvideolLayout.findViewById(R.id.com_interaction_linearlayoutframe);

		mVideoGallery = (OkayPicturesGallery) mvideolLayout.findViewById(R.id.com_outsideinfo_gallery);
		mVideoGalleryAdapter = new ViewGalleryAdapter(mContext,flag==0?UIHelper.Video:UIHelper.UrlVideo);
		mVideoGallery.setAdapter(mVideoGalleryAdapter);
 		
		
		mradiolayLayout=(LinearLayout) findViewById(R.id.interaction_activity_radio);
		((TextView)mradiolayLayout.findViewById(R.id.com_outsideinfo_title)).setText(getResources().getString(R.string.takeradio));
		mRadioButton=(Button) mradiolayLayout.findViewById(R.id.com_outsideinfo_add);
		mRadioButton.setBackground(mContext.getResources().getDrawable(R.drawable.com_interaction_radio));
		
 		mBoundradioLayout=(LinearLayout) mradiolayLayout.findViewById(R.id.com_interaction_linearlayoutframe);

		mRadioGallery = (OkayPicturesGallery) mradiolayLayout.findViewById(R.id.com_outsideinfo_gallery);
		mRadioGalleryAdapter = new ViewGalleryAdapter(mContext,flag==0?UIHelper.TEXT:UIHelper.UrlTEXT);
		mRadioGallery.setAdapter(mRadioGalleryAdapter);
		
		mTakephotoButton.setOnClickListener(this);
		mVideoButton.setOnClickListener(this);
		mRadioButton.setOnClickListener(this);
 	}
	@Override
	public void onClick(View v) {
		if (mActivity==null)
		{
//			mActivity=AppManager.getAppManager().currentActivity();
			return;
		}
       if (v.equals(mTakephotoButton))
       {
//    	   takephoto();
    	   selectPhoto();
    	   
       }else if (v.equals(mVideoButton))
       {
    	   UIHelper.videoMethod(mActivity);
    	   setvideoBound();
       }
       else if (v.equals(mRadioButton))
       {
    	   UIHelper.soundRecorderMethod(mActivity);
    	   setradioBound();
       }
	}
	private void takephoto()
	{
		mImagePathString = LoginActivity.mRootString + "/pic/";// 存放照片的文件夹
		File file = new File(mImagePathString);
		file.mkdir();
		String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
				.format(new Date()) + ".jpg";// 照片命名
//		File out = new File(mImagePathString, fileName);
		mImagePathString = mImagePathString + fileName;// 该照片的绝对路径
		
		UIHelper.cameraMethod(mActivity, mImagePathString);
		setphotoBound();
	}
	private void selectPhoto()
	{
		Builder builder=new AlertDialog.Builder(mContext);
		String [] items=new String[]{"拍照","从相册中选择  "};
		builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				  switch (which) {  
                  case 0:{     //拍照
                      takephoto();
                      break;  
                  }  
                  case 1:  
                      doPickPhotoFromGallery2();// 从相册中去获取  
              		setphotoBound();

                      break;  
                  }  				
			}});
		builder.create().show();
	}
    protected void doPickPhotoFromGallery() {
        Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        mActivity.startActivityForResult(i,UIHelper.RESULT_LOAD_IMAGE);
	}
    private void doPickPhotoFromGallery2()
    {
    	   Intent intent = new Intent(Intent.ACTION_GET_CONTENT);  
           intent.addCategory(Intent.CATEGORY_OPENABLE);  
           intent.setType("image/*");  
           mActivity.startActivityForResult(intent, UIHelper.RESULT_LOAD_IMAGE);   
    }
	public List<String> getPhoto()
	{
		return mPhotoGalleryAdapter.getPath();
	}
	public List<String> getVideo()
	{
		return mVideoGalleryAdapter.getPath();
	}
	public List<String> getRadio()
	{
		return mRadioGalleryAdapter.getPath();
	}
	public void addPhoto(String path)
	{
		String pathString=String.copyValueOf(path.toCharArray());
		Bitmap bmBitmap = android.media.ThumbnailUtils.extractThumbnail(
				ImageUtils.getBitmapByPathThumb(pathString), 96,96);
		File file =new File(pathString);
		if (!file.exists())
		{
			Log.v("interaction", "========文件不存在！");
		}
		if (bmBitmap==null)
		{
			Toast.makeText(mContext, "所选的文件无效，请重新选择", 0).show();
			return;
		}
		
		mPhotoGalleryAdapter.addPhoto(bmBitmap,pathString);
		mphotoGallery.setNumColumns(mPhotoGalleryAdapter.getCount());
        layout(mphotoGallery,mPhotoGalleryAdapter);
        setphotoBound();
	}
	public void addVideo(String path)
	{
		Bitmap bmBitmap = android.media.ThumbnailUtils.createVideoThumbnail(path,
						MediaStore.Images.Thumbnails.MICRO_KIND);
       mVideoGalleryAdapter.addPhoto(bmBitmap, path);
       mVideoGallery.setNumColumns(mVideoGalleryAdapter.getCount());
       layout(mVideoGallery, mVideoGalleryAdapter);	
       setvideoBound();
	}
	public void addRadio(String path)
	{
        mRadioGalleryAdapter.addStrings("录音"+FileUtils.getFileName(path), path);
        mRadioGallery.setNumColumns(mRadioGalleryAdapter.getCount());
        layout(mRadioGallery, mRadioGalleryAdapter);
        setradioBound();
	}
	public void addFileUrl(String url,int type)
	{
		switch (type) {
		case UIHelper.UrlGALLERY:
			mPhotoGalleryAdapter.addUrlfiles(url);
			mphotoGallery.setNumColumns(mPhotoGalleryAdapter.getCount());
	        layout(mphotoGallery,mPhotoGalleryAdapter);
	        setphotoBound();
		break;
		case UIHelper.UrlTEXT:
	        mRadioGalleryAdapter.addUrlfiles(url);
	        mRadioGallery.setNumColumns(mRadioGalleryAdapter.getCount());
	        layout(mRadioGallery, mRadioGalleryAdapter);
	        setradioBound();
	    break;
		case UIHelper.UrlVideo:
	        mVideoGalleryAdapter.addUrlfiles(url);
	        mVideoGallery.setNumColumns(mVideoGalleryAdapter.getCount());
	        layout(mVideoGallery, mVideoGalleryAdapter);
	        setvideoBound();
	    break;
		default:
			break;
		}
	}
	public void setMovement(boolean isEnable)
	{
		mTakephotoButton.setEnabled(isEnable);
		mVideoButton.setEnabled(isEnable);
		mRadioButton.setEnabled(isEnable);
	}
	public void setPhotoOnly()
	{
		mVideoButton.setVisibility(View.GONE);
		mRadioButton.setVisibility(View.GONE);
	}
	public void setVideoOnly()
	{
		mTakephotoButton.setVisibility(View.GONE);
		mRadioButton.setVisibility(View.GONE);
	}
	public void setRedioOnly()
	{
		mTakephotoButton.setVisibility(View.GONE);
		mVideoButton.setVisibility(View.GONE);
	}
	public void setBrown()
	{
		mTakephotoButton.setVisibility(GONE);
		mVideoButton.setVisibility(GONE);
		mRadioButton.setVisibility(GONE);
		if (mPhotoGalleryAdapter.getCount()==0)
			mtakephotoLayout.setVisibility(GONE);
		if (mVideoGalleryAdapter.getCount()==0)
			mvideolLayout.setVisibility(GONE);
		if (mRadioGalleryAdapter.getCount()==0)
			mradiolayLayout.setVisibility(GONE);
	}
	private void setphotoBound()
	{
		mBoundphotoLayout.setBackground(mContext.getResources().getDrawable(R.drawable.com_controlframe));
	}
	private void setvideoBound()
	{
		mBoundvideoLayout.setBackground(mContext.getResources().getDrawable(R.drawable.com_controlframe));

	}
	private void setradioBound()
	{
		mBoundradioLayout.setBackground(mContext.getResources().getDrawable(R.drawable.com_controlframe));

	}*/
}
